package com.company.nuwa.common.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @description:根据经纬度计算距离
 * @date: 2023年5月16日11:50:25
 * @author: gpt
 * @modified:
 * @version:
 */
public class DistanceCalculator {
    private static final double EARTH_RADIUS = 6371.0; // 地球半径，单位为千米

    public static BigDecimal calculateDistance(String lat1, String lon1, String lat2, String lon2) {
        return calculateDistance(new BigDecimal(lat1).doubleValue(), new BigDecimal(lon1).doubleValue(), new BigDecimal(lat2).doubleValue(), new BigDecimal(lon2).doubleValue());
    }

    public static BigDecimal calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        // 将经纬度转换为弧度
        double radLat1 = Math.toRadians(lat1);
        double radLon1 = Math.toRadians(lon1);
        double radLat2 = Math.toRadians(lat2);
        double radLon2 = Math.toRadians(lon2);

        // 使用Haversine公式计算距离
        double dlon = radLon2 - radLon1;
        double dlat = radLat2 - radLat1;
        double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(dlon / 2), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = EARTH_RADIUS * c;


        return  new BigDecimal(distance).setScale(3, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        double lon1 = 121.324549;
        double lat1 = 31.210538;
        double lon2 = 121.322693;
        double lat2 = 31.201578;

        BigDecimal distance = calculateDistance(lat1, lon1, lat2, lon2);
        System.out.println("Distance between user and store: " + distance.doubleValue() + " km");
    }
}
